package com.gin.no_gay_alliance.utils;

import android.content.Context;
import android.content.DialogInterface;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.app.MyApplication;
import com.tencent.bugly.crashreport.CrashReport;

/**
 * Bugly 工具类
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/9/16 21:22
 **/
public class BuglyUtils {
    /**
     * 用户是否授权启动BUGLY
     */
    public static final String DATA_STORE_BUGLY_PERMISSION = "BUGLY_PERMISSION";
    /**
     * 是否已向用户请求授权收集信息
     */
    public static final String DATA_STORE_BUGLY_SHOWN = "BUGLY_SHOWN";
    /**
     * 链接
     */
    public static final String HTML = "<a href='https://document-75651.gzc.vod.tencent-cloud.com/70270bcd-a108-48d0-822c-5b98305c7ada.pdf'>Bugly SDK个人信息保护规则</a>";
    private static final String TAG = BuglyUtils.class.getSimpleName();

    public static void buglyConfirm(Context context) {
        // 是否已显示过授权请求
        Boolean shown = DataStoreUtils.getInstance().get(DATA_STORE_BUGLY_SHOWN, false);
        if (shown) {
            // 已授权时才启动bugly
            if (hasPermission()) {
                Log.d(TAG, "BUGLY SDK 启动");
                CrashReport.initCrashReport(MyApplication.app);
            }
            return;
        }

        AlertDialogUtils.showConfirm(context,
                "BUGLY_SDK",
                context.getString(R.string.tips_bugly_permission),
                buildRuleTextView(context),
                (d, which) -> {
                    if (which == DialogInterface.BUTTON_POSITIVE) {
                        // 用户已授权
                        setHasPermission(true);
                        Log.d(TAG, "BUGLY SDK 启动");
                        CrashReport.initCrashReport(MyApplication.app);
                    }
                });
        DataStoreUtils.getInstance().set(DATA_STORE_BUGLY_SHOWN, true);
    }

    public static void setHasPermission(boolean hasPermission) {
        DataStoreUtils.getInstance().set(DATA_STORE_BUGLY_PERMISSION, hasPermission);
    }

    public static Boolean hasPermission() {
        return DataStoreUtils.getInstance().get(DATA_STORE_BUGLY_PERMISSION, false);
    }

    @NonNull
    public static TextView buildRuleTextView(Context context) {
        TextView tv = new TextView(context);
        tv.setText(Html.fromHtml(HTML, Html.FROM_HTML_MODE_COMPACT));
        tv.setMovementMethod(LinkMovementMethod.getInstance());
        return tv;
    }
}
